import { msGridColRow } from '../utils';
import { Popover } from 'antd';
import styles from './index.less';
import classNames from 'classnames';
import { accSub } from '@/utils/math';
import { showLogin } from '@/hooks/login';
import OrderPayModal, { PayCode, PaySuccess } from '../OrderPayModal';
import AuthModal, { AuthResult } from '../AuthModal';
import { allGet } from '@/services/pc';
import { message } from 'antd';
import { useEffect, useRef } from 'react';
import { history } from 'umi';
import request from '@/utils/request';
import useBuy from '@/hooks/useBuy';
import { apiUrl } from '@/common/const';

const PackageDetail = (props) => {
  const column = props.number >= 3 ? 3 : props.number;

  return (
    <div className={styles['package-detail']} onClick={(e) => e.stopPropagation()}>
      <div className={styles.main}>
        {/* bug
        @info: 
        配合Popover的时候，最右侧的，不给最小宽度，会导致点宽度不够，子元素塌陷到第二行
        @fixbug:
        $number =  数量 3 >= 3 ? 3 : 数量
        最小宽度公式 493 / 3 * $number
      */}

        <div className={styles.list} style={{ minWidth: (493 / 3) * column }}>
          {props?.courses?.map((item) => {
            return (
              <div className={styles.item} key={item.scid}>
                <div
                  className={styles.imgwrapper}
                  onClick={() => window.open(`/center/courses/detail/${item.classid}`)}
                >
                  <div className={styles.img} style={{ backgroundImage: `url(${item.pic})` }} />
                </div>
                <div
                  className={styles.title}
                  onClick={() => window.open(`/center/courses/detail/${item.classid}`)}
                >
                  {item.name}
                </div>
                <div className={styles.money}>
                  ¥<strong>{item.price}</strong>
                </div>
              </div>
            );
          })}
        </div>
      </div>
      <div className={styles.footer}>
        <div className={styles.left}>
          <div className={styles.row}>
            <span className={styles.key}>套餐价格：</span>
            <span className={styles.value}>
              ¥ <strong>{props.mixprices}</strong>
            </span>
          </div>
          <div className={styles.row}>
            <span className={styles.key}>立省：</span>
            <span className={styles.value}>¥{accSub(props.prices, props.mixprices)}</span>
          </div>
        </div>
        <div className={styles.button} onClick={props.onBuy}>
          立即购买
        </div>
      </div>
    </div>
  );
};

interface PackageItemProps {
  index: number;
  number: number;
}
export const PackageItem: React.FC<PackageItemProps> = ({ index, number, ...props }) => {
  const anyProps = props as any;
  const courses = anyProps.courses || [];

  // 认证
  const handleAuth = () => {
    AuthModal.show({
      onSuccess: async (values, type) => {
        AuthResult.show({
          buttonText: '签署合同',
          onClick: () => {
            history.push('/learning?index=3');
          },
        });
      },
    });
  };

  // 获取支付二维码
  const payStatusDetail = ({ balance, payType, fqiNum }) =>
    allGet({
      params: {
        mod: 'salesmix',
        do: 'add',
        balance,
        paysubmit: 1,
        version: 'pc1.0',
        paytype: payType,
        fqipay_num: fqiNum,
        sid: sid || anyProps.sid,
      },
    });

  // 支付查询状态
  const timer = useRef<any>(null);
  const checkPayStatus = async ({ paramsString, balance, payType, fqiNum, manual = false }) => {
    // 检查支付成没
    const checkResponse = await request.get(`${apiUrl}?${paramsString}`);

    // 手动点击已经完成支付按钮
    if (manual) {
      clearInterval(timer.current);
      PayCodeRef.current?.close?.();
      if (checkResponse?.data?.status !== 1) {
        return message.error('支付失败');
      }
      handleShowResult();
      return;
    }
    // 支付成功
    if (checkResponse?.data?.status == 1) {
      clearInterval(timer.current);
      handleShowResult();
    }
  };

  // 支付成功弹窗
  const handlePaySuccess = async (type) => {
    debugger;
    PaySuccess.show({
      data: [],
      type,

      // 去课程
      onGoCourse: () => {
        history.push('/learning');
      },
      // 开具发票
      onGoInvoice: () => {
        history.push('/learning?index=4');
      },
      // 点击实名认证
      onAuth: handleAuth,
      // 点击签署合同
      onSign: () => {
        history.push('/learning?index=3');
      },
    });
  };

  // '':正常
  // verify: 显示实名认证
  // contract: 显示签署合同
  const gotoRef = useRef('');
  // 支付状态判断
  const handleShowResult = () => {
    // 1 正常 2 显示实名认证 3 显示签署合同
    let type = 1;

    if (gotoRef.current === 'contract') {
      type = 3;
    }
    if (gotoRef.current === 'verify') {
      type = 2;
    }
    PayCodeRef.current?.close?.();
    handlePaySuccess(type);

    return true;
  };

  // 显示二维码弹窗
  const PayCodeRef = useRef<any>({});
  const handlePay = async ({ payMoney, payType, fqiNum = 0, useBalance, balance }) => {
    // const response = {
    //   success: true, data: {
    //     check: 'https://www.cgjoy.com/app.php?mod=pay&do=check&version=pc1.0&orderid=20220726142307MvGYJI8CxxxzgCcz2j',
    //     qr: '',
    //   }
    // }

    // const response = {"success":true,"code":0,"data":{"status":1,"msg":"\u4ed8\u6b3e\u6210\u529f\uff0c\u6211\u4eec\u5bf9\u5b66\u5458\u8981\u6c42\u8eab\u4efd\u8ba4\u8bc1\uff0c\u5c06\u4e2d\u8f6c\u5230\u8eab\u4efd\u8ba4\u8bc1\u9875\u9762\u3002","goto":"verify"}}

    const response = await payStatusDetail({ balance, payType, fqiNum });
    if (!response.success) {
      return message.error(response?.data || '显示支付码失败');
    }
    // 记录需要实名认证还是签署合同状态
    gotoRef.current = response?.data?.goto;

    // 余额抵扣实际支付费用，直接支付成功
    if (response?.data?.status == 1) {
      clearInterval(timer.current);
      handleShowResult();
      return;
    }

    // 不然就是返回二维码，然后去轮询
    const check = response?.data?.check || '';
    const arr = check.split('?');
    const paramsString = arr[arr.length - 1];
    PayCodeRef.current = PayCode.showPayCode({
      type: payType,
      data: {
        money: payMoney,
        qrCode: response?.data?.qr,
      },
      onClose: () => {
        clearInterval(timer.current);
      },
      onSuccess: async () => {
        checkPayStatus({ paramsString, balance, payType, fqiNum, manual: true });
      },
    });
    // 轮询支付状态
    timer.current = setInterval(
      () => checkPayStatus({ paramsString, balance, payType, fqiNum }),
      3000,
    );
  };
  // 测试id
  const sid = '96';

  // 获取订单详情
  const getDetail = async (item) => {
    const response = await allGet({
      params: { mod: 'salesmix', do: 'add', version: 'pc1.0', sid: sid || item.sid },
    });
    return response;
  };

  const { packagesBuy } = useBuy();

  const handleBuy = async (item) => {
    const detail = await getDetail(item);
    if (!detail.success) return message.error(detail?.data || '获取订单详情失败');
    const data = detail?.data?.salesmix_class || [];
    OrderPayModal.showOrderPay({
      payPrice: detail?.data?.topay,
      originalPrice: detail?.data?.salesmix?.maxprice,
      balance: detail?.data?.paycredit,
      coupon: detail?.data?.paycredit || 0,
      oldStudentCoupon: 150,
      data,
      onPay: handlePay,
      fqOptions: detail?.data?.fqipay_fqs,
    });
  };

  return (
    <div className={classNames('cgjoy--package-item', styles.item)}>
      <div
        className={classNames('cgjoy--package-item-wrapper', styles['cgjoy--package-item-wrapper'])}
      >
        <div className={classNames(styles.ratio, 'cgjoy--package-item-ratio')}>
          <div className={classNames(styles.content, styles[`type${number}`])}>
            {courses.map((_item) => (
              <span
                key={_item.classid}
                className={styles.img}
                style={{ backgroundImage: `url(${_item.pic})` }}
              />
            ))}
          </div>
          <div className={styles.hover}>
            <i className={styles.mask} />
            <div className={styles.hovermain}>
              <div className={styles.row}>
                套餐价格：
                <div className={styles.price}>
                  <span className={styles.unit}>¥</span>
                  <span className={styles.text}>{anyProps.mixprices}</span>
                </div>
              </div>
              <div className="row">立省：¥{accSub(anyProps.prices, anyProps.mixprices)}</div>
              <div
                className={classNames(styles.buy, 'cgjoy--package-item-hovermain-buy')}
                onClick={() => packagesBuy(anyProps)}
              >
                立即购买
              </div>
            </div>
          </div>
        </div>
        <div className={classNames('cgjoy--package-item-content')}>
          <div className={classNames(styles.title, 'cgjoy--package-item-content-title')}>
            <span className={classNames(styles.text, 'cgjoy--package-item-content-text')}>
              {anyProps?.subject}
            </span>
            <Popover
              zIndex={3}
              getPopupContainer={() => document.getElementById('zhy-layout-container')!}
              overlayClassName={styles['package-detail-propover']}
              placement="top"
              trigger="hover"
              content={
                <PackageDetail number={number} onBuy={() => packagesBuy(anyProps)} {...props} />
              }
              title={() => null}
            >
              <i
                className={classNames(
                  styles.detailbutton,
                  'cgjoy--package-item-content-detailbutton',
                )}
              />
            </Popover>
          </div>
          <div className={classNames(styles.info, 'cgjoy--package-item-content-info')}>
            套餐内有课程 <span className={styles.number}>{number}个</span>
          </div>
          <div className={styles.price}>
            <span className={classNames(styles.unit, 'cgjoy--package-item-content-unit')}>¥</span>
            <span className={classNames(styles.text, 'cgjoy--package-item-content-price-text')}>
              {anyProps.mixprices}
            </span>
          </div>
        </div>
      </div>
    </div>
  );
};

interface PackageProps {
  data: any[];
  itemKey: string;
}

const Package: React.FC<PackageProps> = ({ data = [], itemKey }) => {
  return (
    <div className={classNames('cgjoy--package', styles.package)}>
      {data?.map((item, index) => (
        <PackageItem key={item[itemKey]} index={index} number={item?.courses?.length} {...item} />
      ))}
    </div>
  );
};
export default Package;
